package experiment5.demo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketHandler extends Thread {
    String clientName = "";
    Socket socket;
    PrintWriter writer;

    public SocketHandler(Socket socket) {
        this.socket = socket;
        this.clientName = "<" + socket.getInetAddress().toString() + "_" + socket.getPort() + ">";
        System.out.println(this.clientName + "  连接成功！");
        try {
            writer = new PrintWriter(this.socket.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sayTo(String content) {
        writer.println(content);
        writer.flush();
    }

    public void run() {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String info = null;
            while ((info = reader.readLine()) != null) {
                System.out.println(this.clientName + ":" + info);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
